package flc.ast.fragment.edit;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.ImgEditActivity;
import com.stark.imgedit.ModuleConfig;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.CustomPaintView;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseEditFragment;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.FragmentPaintBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PaintFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PaintFragment extends BaseEditFragment<FragmentPaintBinding> {

    public static final int INDEX = ModuleConfig.INDEX_PAINT;
    private CustomPaintView mPaintView;

    private int color = Color.BLACK;
    private int paintWidth = 5;
    private ColorAdapter colorAdapter;
    private int oldPosition = 0;

    public static PaintFragment newInstance() {
        PaintFragment fragment = new PaintFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        mImgEditActivity.mode = ImgEditActivity.MODE_PAINT;
        mImgEditActivity.mImgView.setImageBitmap(mImgEditActivity.getMainBit());
        mPaintView.setVisibility(View.VISIBLE);
        mPaintView.setEraser(false);
        updatePaintView();
    }

    @Override
    public void backToMain() {
        mImgEditActivity.mode = ImgEditActivity.MODE_NONE;
        mImgEditActivity.mImgView.setVisibility(View.VISIBLE);
        mPaintView.setVisibility(View.GONE);
        mPaintView.reset();
        mImgEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_paint;
    }

    @Override
    protected void initView() {
        oldPosition = 0;
        mPaintView = mImgEditActivity.mPaintView;
        initSeekBar();
        onShow();

        mDataBinding.rvColor.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvColor.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);

        mPaintView.setColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#000000", true));
        listColor.add(new MyColorBean("#FFFFFF", false));
        listColor.add(new MyColorBean("#E12D2D", false));
        listColor.add(new MyColorBean("#FFA8A8", false));
        listColor.add(new MyColorBean("#FFB652", false));
        listColor.add(new MyColorBean("#FFF62C", false));
        listColor.add(new MyColorBean("#79BA56", false));
        listColor.add(new MyColorBean("#35B9B0", false));
        listColor.add(new MyColorBean("#3F68BC", false));
        listColor.add(new MyColorBean("#9F45F1", false));
        listColor.add(new MyColorBean("#E85C90", false));
        listColor.add(new MyColorBean("#C0C0C0", false));
        listColor.add(new MyColorBean("#CA58C9", false));
        listColor.add(new MyColorBean("#8A72E1", false));
        listColor.add(new MyColorBean("#46D5AF", false));
        listColor.add(new MyColorBean("#5E8C4F", false));
        colorAdapter.setList(listColor);
    }

    private void initSeekBar() {
        mDataBinding.sbPenSize.setMax(10);
        mDataBinding.sbPenSize.setProgress(0);
        mDataBinding.sbPenSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                paintWidth = 5 + progress * 2;
                updatePaintView();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }


    private void updatePaintView() {
        mPaintView.setEraser(false);
        this.mPaintView.setColor(color);
        this.mPaintView.setWidth(paintWidth);
    }

    /**
     * 保存涂鸦
     */
    public void applyPaintImage() {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Matrix touchMatrix = mImgEditActivity.mImgView.getImageViewMatrix();

                Bitmap retBitmap = Bitmap.createBitmap(mImgEditActivity.getMainBit()).copy(
                        Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(retBitmap);

                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());

                float[] f = new float[9];
                m.getValues(f);
                int dx = (int) f[Matrix.MTRANS_X];
                int dy = (int) f[Matrix.MTRANS_Y];
                float scale_x = f[Matrix.MSCALE_X];
                float scale_y = f[Matrix.MSCALE_Y];
                canvas.save();
                canvas.translate(dx, dy);
                canvas.scale(scale_x, scale_y);

                if (mPaintView.getPaintBit() != null) {
                    canvas.drawBitmap(mPaintView.getPaintBit(), 0, 0, null);
                }
                canvas.restore();

                emitter.onNext(retBitmap);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (bitmap != null) {
                    mImgEditActivity.changeMainBitmap(bitmap, true);
                }
                mPaintView.reset();
                backToMain();
            }
        });

    }

}